/*
 * @Date: 2023-02-28 20:00:51
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-14 21:29:33
 * @FilePath: \A19\backend\src\utils\msgsForGame\gameMsgImplements.ts
 */
import { WsServer, WsConnection } from 'tsrpc';
import { ServiceType } from "../../shared/protocols/serviceProto";
import { Live, player } from '../Classes/Live';

export function gameMsgImplements(wsserver: WsServer<ServiceType>) {
    wsserver.listenMsg('AMessages/Game/UpdateStatus',call =>{
        const live = Live.lives.find(live => live.courseId.equals(call.msg.liveId))
        if(!live) return

        const player = live.players.find(player => player.playerId.equals(call.msg.playerId))
        if(player){
            Object.assign(player,call.msg)
        }
       
        wsserver.broadcastMsg('AMessages/Game/UpdateStatus',call.msg,live.players.map(p => p.connection));
    })

    wsserver.listenMsg('AMessages/Game/PlayerJoin', call =>{
        const live = Live.lives.find(live => live.courseId.equals(call.msg.liveId))
        if(!live) return

        live.players.push({
            connection: call.conn as WsConnection,
            liveId: call.msg.liveId,
            playerId: call.msg.playerId,
            playerName: call.msg.playerName,
            x:0,
            y:-968.56,
            z:0,
            strideForward:0,
            strideRight:0,
            animation: 'idle',
            rotationX: 0,
            rotationY: 0,
            rotationZ: 0,
            model:call.msg.model
        })

        wsserver.broadcastMsg('AMessages/Game/PlayerJoin',call.msg,live.players.map(p => p.connection));
        live.players.forEach((player) =>{
            (call.conn as WsConnection<ServiceType>).sendMsg('AMessages/Game/PlayerJoin',player)
        })
    })

    wsserver.listenMsg('AMessages/Game/PlayerLeave',call =>{
        const live = Live.lives.find(live => live.courseId.equals(call.msg.liveId))
        if(live){
            const student = live.players.find((player,index,array) => {
                if(player.playerId.equals(call.msg.playerId)){
                    array.splice(index,1)
                    return true
                }
                return false
            })
            if(!student) return
            console.log(student.playerName + " offline");

            wsserver.broadcastMsg(
                'AMessages/Game/PlayerLeave',
                call.msg,live.players.map(s => s.connection)
            )
        }
    })
}